//
//  THNetworkTools+Login.swift
//  tripartiteTestDemo
//
//  Created by rimi on 2017/5/19.
//  Copyright © 2017年 rimi. All rights reserved.
//

import Foundation

typealias loginCallback = (_ success:Bool, _ errorInfo:String) -> Void
let weiboAppKey = "1096580531"
let weiboAppSecret = "64948338ca2de0fdace1e81a60390723"
let weiboRedirectURL = "http://www.baidu.com"

extension THNetworkTools {
    
    
    /// 账号登录
    ///
    /// - Parameters:
    ///   - userName: 用户名
    ///   - password: 密码
    ///   - finish: 完成回调
    func requestWithAccountLogin(userName:String, password:String, finish:loginCallback?) {
        // 登录请求
        request(method: "user", action: "userLogin", params: ["sUsername":userName,"sPassword":password.md5()]) { (data, error) in
          
            guard let dict = data?["data"] as? [String:Any] else {
                finish?(false, data?["errMessage"] as! String)
                return
            }
            // 将用户数据保存的单例对象中
            THUserLoinInfo.currentUser.setValuesForKeys(dict)
            // 记录登录状态
            UserDefaults.standard.set(true, forKey: kUserIsLoginKey)
            // 回调成功
            finish?(true,data?["message"] as! String)
        }
    }
    
    
    /// 微博三方登录
    ///
    /// - Parameter finish: 完成回调
    func requestWithWeiboLogin(finish:loginCallback?) {
        // 注册(使用的三方OpenShare封装方法)
        OpenShare.connectWeibo(withAppKey: weiboAppKey, appSecret: weiboAppSecret, redirectURI: weiboRedirectURL)
        // 微博账号登录授权(使用的三方OpenShare封装方法)
        OpenShare.weiboAuth("all", redirectURI: weiboRedirectURL, success: { (dict) in
            guard let dict = dict else {
                return
            }
            // 获得token和用户id
            let accessToken = dict["accessToken"] as! String
            let uid = dict["userID"] as! String
            // 微博用户数据请求接口 接口文档网页http://open.weibo.com/wiki/2/users/show
            let url = "https://api.weibo.com/2/users/show.json?access_token=\(accessToken)&uid=\(uid)"
            // 请求微博用户数据信息(使用的AFN的get方法请求数据)
            self.get(url, parameters: nil, progress: nil, success: { (_, userInfo) in
                guard let dict = userInfo as? [String: Any] else {
                    return
                }
                // 获得需要的微博用户数据
                let sOpenId = dict["id"] as! Int
                let sNickname = dict["name"] as! String
                let sFigureImgUrl = dict["profile_image_url"] as! String
                // 使用获得的微博用户数据登录当前应用
                let params: [String:Any] = ["sMod":"新浪微博",
                              "sCallbackType":"login",
                              "sOpenId":sOpenId,
                              "sNickname":sNickname,
                              "sFigureImgUrl":sFigureImgUrl]
                
                // 使用封装的接口方法登录
                self.request(method: "user", action: "userThreadLogin",params: params, finished: { (data, error) in
                    guard let dict = data?["data"] as? [String:Any] else {
                        finish?(false, data?["errMessage"] as! String)
                        return
                    }
                    // 将用户数据保存的单例对象中
                    THUserLoinInfo.currentUser.setValuesForKeys(dict)
                    // 记录登录状态
                    UserDefaults.standard.set(true, forKey: kUserIsLoginKey)
                    // 回调成功
                    finish?(true,data?["message"] as! String)

                })
            }) { (_, error) in
                finish?(false,"微博用户数据请求失败")
            }
            
        }, fail: { (dict, err) in
            print("+++++++++",dict!,err!)
            finish?(false,"微博三方授权异常")
        })
    }
    
}
